package com.coolweather.android.service

import android.app.AlarmManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.SystemClock
import androidx.preference.PreferenceManager
import com.coolweather.android.util.HttpUtil
import com.coolweather.android.util.Utility
import okhttp3.Call
import okhttp3.Response
import java.io.IOException

/**
 * 服务
 */
class AutoUpdateService : Service() {

    override fun onBind(intent: Intent): Nothing? = null

    /**
     * 服务每次启动都会调用
     */
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        updateWeather()
        updateBingPic()
        // 8小时 毫秒数
        val anHour = 8 * 60 * 60 * 1000
        val triggerAtTime = SystemClock.elapsedRealtime() + anHour
        val serviceIntent = Intent(this, AutoUpdateService::class.java)
        val pi = PendingIntent.getService(this, 0, serviceIntent, 0)
        (getSystemService(Context.ALARM_SERVICE) as AlarmManager).apply {
            cancel(pi)
            set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi)
        }
        return super.onStartCommand(intent, flags, startId)
    }


    /**
     * 更新背景图
     */
    private fun updateBingPic() {
        val requestPicUrl = "http://guolin.tech/api/bing_pic"
        HttpUtil.sendOkHttpRequest(requestPicUrl, object : okhttp3.Callback {
            override fun onResponse(call: Call, response: Response) {
                val picUrl = response.body!!.string()
                PreferenceManager.getDefaultSharedPreferences(this@AutoUpdateService).edit().apply {
                    putString("bing_pic", picUrl)
                }.apply()
            }

            override fun onFailure(call: Call, e: IOException) {
                e.printStackTrace()
            }
        })
    }

    /**
     * 更新天气信息
     */
    private fun updateWeather() {
        val weatherString = PreferenceManager.getDefaultSharedPreferences(this)
            .getString("weather", null)
        if (weatherString != null) {
            val weather = Utility.handleWeatherResponse(weatherString)
            val weatherId = weather.basic.weatherId
            val requestWeatherUrl =
                "http://guolin.tech/api/weather?cityid=$weatherId&key=1f841d83882f475e97c4ab8f0eaee7cf"
            HttpUtil.sendOkHttpRequest(requestWeatherUrl, object : okhttp3.Callback {

                override fun onResponse(call: Call, response: Response) {
                    val responseText = response.body!!.string()
                    val weatherRes = Utility.handleWeatherResponse(responseText)
                    if ("ok" == weatherRes.status) {
                        PreferenceManager.getDefaultSharedPreferences(this@AutoUpdateService).edit().apply {
                            putString("weather", responseText)
                        }.apply()
                    }
                }

                override fun onFailure(call: Call, e: IOException) {
                    e.printStackTrace()
                }
            })
        }

    }
}
